<template>
  <div class="content">
    <div class="goback" @click="goback">
      <img src="@/assets/images/home/返回 (2).png" alt="" />
      <p class="font18 fw400">{{ t("作品库") }}</p>
    </div>
    <div class="bottom">
      <div class="types">
        <el-menu
          default-active="0"
          class="el-menu-vertical-demo"
          @select="mode_select($event)"
        >
          <el-submenu index="111" style="margin-top: 26px">
            <template slot="title">
              <h3
                class="font20"
                style="font-weight: 500; font-size: 20px; color: #222222"
              >
                {{ t("选择手机型号") }}
              </h3>
            </template>
            <el-menu-item-group>
              <el-menu-item
                v-for="(item, idx) in modeList"
                :key="idx"
                :index="idx + ''"
              >
                {{ item.name }}
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </div>

      <div class="right">
        <div class="show">
          <div class="img-actions" v-if="divide_up_img_select != -1">
            <el-button class="color-222" @click="divide_up_imgs_delete()">{{
              $t("公共.删除")
            }}</el-button>
            <el-button class="color-222" @click="divide_up_img_select = -1">{{
              $t("公共.取消")
            }}</el-button>
            <el-button class="color-red" @click="show_dialog = true">{{
              $t("公共.确定")
            }}</el-button>
          </div>
          <div class="make-area" v-loading="phone_case_making" ref="makeArea">
            <img
              :style="{
                position: 'absolute',
                top: creamimgtop * 4.5 + 'px',
                left: creamimgleft * 4.5 + 'px',
                width: creamwidth * 8 + 'px',
                height: creamheight * 8 + 'px',
                'z-index': '10',
              }"
              :src="(creamimg + `?${new Date().getTime()}`) | imgSrc"
              alt=""
              crossorigin="anonymous"
            />
            <img
              class="bg-img"
              :src="(phoneDesign.bg_img + `?${new Date().getTime()}`) | imgSrc"
              alt=""
              crossorigin="anonymous"
            />
            <template v-if="phoneDesign.divide_item">
              <div
                class="divide-list"
                :style="{
                  'grid-template-columns': `repeat(${phoneDesign.divide_item.column}, 1fr)`,
                  'grid-template-rows': `repeat(${phoneDesign.divide_item.row}, 1fr)`,
                  gap: phone_case_making ? '0px' : '1px',
                }"
              >
                <span
                  class="divide-item"
                  :class="phone_case_making ? 'divide-item-hide' : ''"
                  @click="divide_item_click($event, item, index)"
                  :active="divide_up_img_select == index"
                  v-for="(item, index) in phoneDesign.divide_imgs"
                  :key="index"
                >
                  <input class="file-input" type="file" accept="image/*" />
                  <img class="section-img" v-if="item.img" :src="item.img" />
                </span>
              </div>
            </template>

            <img
              class="shell-img"
              v-if="phoneDesign.shell_img"
              :src="
                (phoneDesign.shell_img + `?${new Date().getTime()}`) | imgSrc
              "
              alt=""
              crossorigin="anonymous"
            />
          </div>
          <div class="namecheck">
            <img
              class="actionImg"
              src="@/assets/images/home/left (2).png"
              alt=""
              style="width: 15px; height: 27px"
              @click="left"
            />
            <div class="list" ref="imgs">
              <ul class="nameList">
                <li
                  v-for="item in nameList"
                  :key="item.id"
                  @click="name_item_click(item)"
                  :class="phoneDesign.shell_id == item.id ? 'active' : ''"
                >
                  <img class="item-cover" :src="item.image | imgSrc" alt="" />
                  <p class="tcenter font16">{{ item.phone_case_name }}</p>
                </li>
              </ul>
            </div>
            <img
              class="actionImg"
              src="@/assets/images/home/right (2).png"
              alt=""
              style="width: 15px; height: 27px"
              @click="right"
            />
          </div>
        </div>
        <div class="swiper">
          <ul>
            <li
              v-for="(item, index) in divide_up_list"
              :key="item.id"
              @click="divide_up_click(index)"
            >
              <img :src="item.image" alt="" />
            </li>
          </ul>
        </div>
      </div>
    </div>
    <el-dialog
      class="dialog"
      :title="t('编辑完成')"
      :visible.sync="show_dialog"
      width="30%"
    >
      <div
        style="
          display: flex;
          align-items: center;
          margin-bottom: 30px;
          justify-content: center;
        "
      >
        <h3>作品名称:</h3>
        <el-input
          style="width: 200px"
          v-model="works_name"
          placeholder="请输入作品内容"
        ></el-input>
      </div>
      <div class="dialog-content">{{ t("图片编辑成功，是否保存") }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="dialog-cancel-btn" @click="show_dialog = false">{{
          $t("再想想")
        }}</el-button>
        <el-button class="dialog-confim-btn" @click="make_img_click()">{{
          $t("是")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getWorksList,
  getGoodsModelTwo,
  getPhoneCaseList,
  upImage,
  addWorks,
} from "@/utils/api";
import html2canvas from "@/utils/html2canvas.min.js";
export default {
  components: {},
  data() {
    //这里存放数据
    return {
      creamimg: "",
      creamimgtop: "", //相机距顶部的位置
      creamimgleft: "", // 相机距左边的位置
      creamwidth: "", // 相机的宽度
      creamheight: "", // 相机的高度
      works_name: "", //用户上传的作品名称
      modeList: [],
      phoneDesign: {
        width: 0,
        heigh: 0,
      },
      nameList: [],
      show: 1,
      divide_up_list: [
        {
          id: 1,
          image: require("../../assets/images/mine/layout_icon_twins.png"),
          column: 1,
          row: 2,
        },
        {
          id: 2,
          image: require("../../assets/images/mine/layout_icon_single.png"),
          column: 1,
          row: 1,
        },
        {
          id: 3,
          image: require("../../assets/images/mine/layout_icon_brockmann2.png"),
          column: 4,
          row: 6,
        },
        {
          id: 4,
          image: require("../../assets/images/mine/layout_icon_8rectangle.png"),
          column: 2,
          row: 4,
        },
        {
          id: 5,
          image: require("../../assets/images/mine/layout_icon_brockmann.png"),
          column: 3,
          row: 5,
        },
      ],
      divide_up_select: 0,
      divide_up_img_select: -1,
      phone_case_making: false,
      show_dialog: false,
    };
  },
  created() {
    this.phone_case_making = true;
    // 获取手机的模型
    getGoodsModelTwo({ goods_model_id: this.$route.query.goods_model_id }).then(
      (res) => {
        if (res.code == 1) {
          // console.log("手机的模型----", res.data);
          this.modeList = res.data;
          this.phoneDesign = {
            ...this.phoneDesign,
            width: this.modeList[0].width,
            heigh: this.modeList[0].heigh,
            bg_img: this.modeList[0].image,
            bg_id: this.modeList[0].id,
          };
          this.getPhoneCaseList();
        }
      }
    );
  },
  //方法集合
  methods: {
    /**
     * 简化翻译方法(少写property)
     * @param {String} v 最后一个key值
     */
    t(v) {
      return this.$t(`作品库.${v}`);
    },
    goback() {
      this.$router.go(-1);
    },
    right() {
      this.utils.right(this.$refs.imgs);
    },
    left() {
      this.utils.left(this.$refs.imgs);
    },
    // 模型选择
    mode_select(e) {
      console.log("模型切换---", e);
      let item = this.modeList[e];
      this.creamimg = item.photo_image;
      this.creamimgtop = item.phone_top_space;
      this.creamimgleft = item.phone_left_space;

      this.creamwidth = item.photo_width;
      this.creamheight = item.phone_heigh;
      this.phoneDesign = {
        width: item.width,
        heigh: item.heigh,
        bg_img: item.image,
        bg_id: item.id,
      };
      this.getPhoneCaseList();
    },
    // 获取手机壳列表
    getPhoneCaseList() {
      getPhoneCaseList({ goods_model_id: this.phoneDesign.bg_id }).then(
        (res) => {
          if (res.code == 1) {
            this.nameList = res.data;
            this.divide_up_img_select = -1;
            if (this.nameList.length > 0) {
              this.phoneDesign = {
                ...this.phoneDesign,
                shell_img: this.nameList[0].image,
                shell_id: this.nameList[0].id,
              };
              this.divide_up_click(0);
            }
          }
        }
      );
    },
    name_item_click(item) {
      this.phoneDesign = {
        ...this.phoneDesign,
        shell_id: item.id,
        shell_img: item.image,
      };
      if (!this.phoneDesign.divide_img) {
        this.phoneDesign["divide_item"] = this.divide_up_list[0];
      }
    },
    //选择上传的图片的格式
    divide_up_click(index) {
      this.divide_up_select = index;
      let divide_item = this.divide_up_list[index];
      this.phoneDesign["divide_item"] = divide_item;
      this.phoneDesign["divide_imgs"] = new Array(
        divide_item.row * divide_item.column
      ).fill({});
      // console.log(this.phoneDesign['divide_imgs']);
      this.$forceUpdate();
      this.phone_case_making = false;
    },
    // 未知
    divide_item_click(e, item, index) {
      if (!e.isTrusted) return;
      this.divide_up_img_select = index;
      if (item.index >= 0) return;
      this.phone_case_making = true;
      let el = e.srcElement.children[0];
      // if (item.index >= 0) {
      //     el = e.target.previousSibling;
      // }else {
      //     el = e.srcElement.children[0];
      // }
      setTimeout(() => {
        this.phone_case_making = false;
      }, 500);
      if (!el) return;
      el.onchange = (event1) => {
        // console.log("event1 =>", event1);
        let file = event1.target.files[0];
        const reader = new FileReader();
        reader.onloadend = (event2) => {
          let itemBuff = {};
          itemBuff.img = event2.target.result;
          itemBuff.index = index;
          this.phoneDesign.divide_imgs[index] = itemBuff;
          this.$forceUpdate();
          this.phone_case_making = false;
        };
        reader.readAsDataURL(file);
      };
      el.click();
    },
    // 删除保存的作品
    divide_up_imgs_delete() {
      this.phoneDesign.divide_imgs[this.divide_up_img_select] = {};
      this.$forceUpdate();
    },
    // 保存到作品库
    async make_img_click() {
      if (this.works_name == "") {
        return this.$message.error("请输入作品标题");
      }
      this.phone_case_making = true;
      this.divide_up_img_select = -1;
      this.phoneDesign.divide_imgs.map((e) => (e["hide_bg_color"] = true));
      await this.$nextTick();
      let res1 = await html2canvas(this.$refs.makeArea, {
        useCORS: true,
        backgroundColor: null,
      });
      this.phone_case_making = false;
      // 返回的canvacs标签
      console.log("画下来的图----", res1);

      let base64imgBuffer = this.dataURLtoBlob(res1.toDataURL("image/png"));
      let res2 = await upImage(base64imgBuffer);
      console.log("上穿的图片", res2);
      if (res2.data.code == 1) {
        let res3 = await addWorks({
          works_name: this.works_name,
          phone_case_id: this.phoneDesign.shell_id,
          image: res2.data.data.url,
        });
        if (res3.code == 1) {
          this.$message.success(res3.msg);
          this.$router.go(-1);
        }
      } else {
        this.$message.error(res2.msg);
      }
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.content {
  margin: 20px 110px 0px;
  display: flex;
  flex-direction: column;

  .goback {
    align-self: flex-start;
    display: flex;
    align-items: center;
    cursor: pointer;
    user-select: none;
    margin-top: 38px;
    img {
      width: 16px;
      height: 16px;
    }
  }

  .bottom {
    display: flex;

    .types {
      width: 270px;

      .el-menu {
        margin-top: 20px;
        border-right: 0;
      }
    }

    .right {
      width: 1400px;
      height: 860px;
      flex: 1;
      display: flex;
      // flex-flow: row wrap;
      //   justify-content: space-around;
      user-select: none;

      .show {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-direction: column;
        position: relative;
        width: 1200px;
        margin-left: 218px;
        .img-actions {
          position: absolute;
          display: flex;
          justify-content: space-around;
          align-items: center;
          flex-direction: row;
          gap: 34px;

          .color-222 {
            border: 1px solid #222;
            color: #222;
            background: #fff;
          }

          .color-red {
            background: #ff5757;
            color: #fff;
          }
        }

        .make-area {
          margin-top: 60px;
          position: relative;
          // width: 300px;

          #makeCanvas {
            position: absolute;
            z-index: 1;
          }

          .bg-img {
            width: 100%;
            object-fit: cover;
            z-index: 5;
          }

          .divide-list {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 9;
            display: grid;

            .divide-item {
              background: rgba(100, 100, 100, 0.5);
              overflow: hidden;
              position: relative;

              .file-input {
                opacity: 0;
              }

              .section-img {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }

            .divide-item[active] {
              border: 1px solid #ff5757;
            }

            .divide-item-hide {
              background: rgba(255, 255, 255, 0) !important;
            }
          }

          .shell-img {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            object-fit: fill;
            z-index: 22;
            pointer-events: none;
          }
        }

        .namecheck {
          display: flex;
          margin-top: 67px;
          align-items: center;

          .list {
            width: 710px;
            overflow: hidden;
            // position: relative;

            .nameList {
              display: flex;
              position: relative;

              li {
                width: 96px;
                padding: 0px 12px;
                cursor: pointer;

                .item-cover {
                  margin: 0px 21px;
                  width: 54px;
                  height: 100px;
                  margin-bottom: 10px;
                  object-fit: cover;
                }

                p {
                  width: 96px;
                }
              }

              .active {
                p {
                  position: relative;
                }

                p::after {
                  position: absolute;
                  top: -7px;
                  left: 0;
                  content: "";
                  width: 96px;
                  height: 3px;
                  background-color: #ff5f5f;
                }
              }
            }
          }
        }
      }

      .swiper {
        width: 220px;
        height: 100%;
        overflow: auto;
        margin-left: 183px;

        ul {
          li {
            width: 120px;
            height: 144px;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-bottom: 10px;

            img {
              width: 71px;
              height: 133px;
            }
          }
        }
      }

      .swiper::-webkit-scrollbar {
        width: 6px;
        height: 400px;
        background-color: #eee;
      }

      .swiper::-webkit-scrollbar-thumb {
        background-color: #000;
        border-radius: 10px;
      }
    }
  }

  .pop {
    .dialog-footer {
      button {
        width: 270px;
        height: 55px;
        background: #ff5757;
        border-radius: 10px;
        border: 0;
        color: #fff;
      }
    }
  }

  .dialog {
    /deep/ .el-dialog__title {
      font-weight: bold;
    }

    .dialog-content {
      color: #000;
      font-size: 18px;
      text-align: center;
    }

    .dialog-cancel-btn {
      background: #ff5757;
      width: 170px;
      color: #f9f9f9;
      line-height: 55px;
      border-radius: 10px;
      padding: 0;
    }

    .dialog-confim-btn {
      background: #000000;
      width: 170px;
      color: #f9f9f9;
      line-height: 55px;
      border-radius: 10px;
      padding: 0;
    }
  }
}

/deep/.el-dialog__footer {
  text-align: center !important;
}

.el-menu-item {
  font-weight: 400;
  font-size: 18px;
}

.el-menu-item.is-active {
  color: #ffffff;
  background: #ff5757;
}
</style>
